<?php
namespace app\common\controller;
use \think\Request;

abstract class Base extends \app\common\controller\ApiCommon {
    /**
     * the model name to bind with this controller,you have to override it in the derive class.
     */
	protected $modelname;

	/**
	 * when the index() method is called, this function will be invoked when get the filter condition.
	 * insert the search condition in this abstract function
	 * return false if you would like to support no filter condition.
	 *
	 * @return Array|false
	 */
	protected abstract function _index();


  /**
   * the order filter function for the index command,if you want to have sortable character,you should write this function in your derive class,
   * the function is used for judging whether the field to be sorted is legal.
   * the $field is a reference,it means that you can changed its in derive class to redirect it to sort other field.
   * Tips: this function is a abstract function,you can implements it optionally.
   * @return boolean true means the field can be sorted,
   */
    // protected function _order(&$field);

    /**
     * process all the index request (aim to list the element)
     * the function has some parameter which submit with forms, all of those as follow
     * the filter method is invoking a abstract function(_index()) to implements. you have to implements it after inherit this class.
     * back_type	"list"|"tree"|"tree_child"
	 * 					"list" retrun a list
	 * 					"tree" return a tree,
	 *					"tree_child" return a list, consist of the same parent element,the parent is specific by get method parameter: pid
     * @return json
     */
	public function index() {
		$baseModel=model($this->modelname);
		$back_type=$this->param('back_type','list');
		$condition=$this->_index();
		switch ($back_type) {
		case 'tree':
			$defaultLimit = 0;
			break;
		case 'tree_child':
			$defaultLimit = 0;
			$condition = ['pid' => $this->param('pid',0)];
			break;
    case 'tree_child_first':
      $defaultLimit = 0;
      $pid = intval($this->param('pid',0));
      $tmp = $baseModel->getAllParent([$pid]);
      $tmp[] = $pid;
      $condition = ['id' => $baseModel->getAllBrother($tmp)];
      break;
		default:
			$defaultLimit = 10;
			break;
		}
    $condition['_limit']=$this->param('_limit', $defaultLimit);
    $condition['_page']=$this->param('_page', 1);

    if (method_exists($this, '_order') && isset($this->param['__order'])) {
      $json = json_decode($this->param['__order']);
      if (is_object($json) && isset($json->field) && $this->_order($json->field)) {
        $condition['_order']=['field'=>$json->field,'desc'=>$json->desc==true];
      }
    }

		$data = $baseModel->getDataList($condition);

		if ($back_type == 'tree' || $back_type == 'tree_child_first'){
			if (method_exists($baseModel,'makeTree')) {
				$data=$baseModel->makeTrees($data->toArray());
			} else {
				return json_pack('该资源不支持树状显示',400);
			}
		}

		return json_pack($data);
	}

  /**
   * this function will return the number of the index() return items.,you should put the same parameter as the index(),
   *
   *
   * @return json
   */
	public function count() {
		$baseModel=model($this->modelname);
		$condition=$this->_index();
		return json_pack($baseModel->getDataListCount($condition));
	}

    /**
     * read a single record by id
     * this controller action will return the resources detail information.
     *
     * @return json
     */

	public function read() {
		$baseModel=model($this->modelname);

		if (isset($this->param['id']))
			$data = $baseModel->getDataById($this->param("id"));
		else
			return json_pack("must specify an ID",STATUS_MISS_ID);

		if ($data) {
			return json_pack($data);
		} else {
			return json_pack($baseModel->getError(), STATUS_RESOURCE_NOT_FOUND);
		}
	}

  /**
   * save a record and return the new resource id.
   *
   * @return json
   */
	public function save() {
		$baseModel=model($this->modelname);

		if ($this->param)
			if (($error=$this->validate($this->param,$this->modelname.'.create'))!==true){
				return json_pack($error,400);
			}

		if ($result=$baseModel->createData($this->param)) {
			return json_pack(['id'=>$result]);
		} else {
			return json_pack($baseModel->getError(),STATUS_DEAL_FAIL);
		}
	}

    /**
     * update a resource by its id.
     * if the update action do successfully, will back the message 'ok'
     *
     * @return json
     */
	public function update() {
		$baseModel=model($this->modelname);
		$param = $this->param;


		if (!isset($this->param['id']))
			return json_pack("更新资源必须提交id",STATUS_MISS_ID);

		if ($this->param)
			if (($error=$this->validate($this->param,$this->modelname.'.update'))!==true){
				return json_pack($error,400);
			}

		if ($baseModel->updateDataById($param, $this->param['id'])) {
			return json_pack('OK');
		} else {
			return json_pack($baseModel->getError(),STATUS_PARAM_WRONG);
		}
	}

    /**
     * delete a resource by its id
     * if the delete action do successfully, will back the message 'ok'
     *
     * @return json
     */
	public function delete() {
		$baseModel=model($this->modelname);
		if ($data = $baseModel->delDataById($this->param('id'))) {
			return json_pack("OK");
		} else {
			return json_pack($baseModel->getError(),STATUS_DEAL_FAIL);
		}
	}

	 /**
     * delete a batch of resource by its id,
     * if the deletes action do successfully, will back the message 'ok'
     *
     * @return json
     */
	public function deletes() {
		$baseModel=model($this->modelname);

		if ($baseModel->delDatas($this->param('ids'))) {
			return json_pack("OK");
		} else {
			return json_pack($baseModel->getError(),STATUS_DEAL_FAIL);
		}
	}

	 /**
	 * enables or disables a batch of resource by its id,
	 * if the enables action do successfully, will back the message 'ok'
	 *
	 * @return json
	 */
	public function enables() {
		$baseModel=model($this->modelname);

		$status = $this->param('status');
		if (!($status==1||$status==0))
			return json_pack('status 参数必须为0或1',400);

		$data = $baseModel->enableDatas($this->param('ids'), $status);
		if ($data) {
			return json_pack("OK");
		} else {
			return json_pack($baseModel->getError(),STATUS_DEAL_FAIL);
		}
	}
}

?>